<template>
    <div class="tableRow">
        <el-row class="select-list" v-permission="'system:config:query'">
            <el-form :inline="true" ref="selectForm" :model="selectFormModel" :label-position="'right'"
                     label-width="80px" size="mini" @submit.native.prevent>
                <el-form-item label="参数名称" prop="configName">
                    <el-input v-model="selectFormModel.configName" placeholder="参数名称" style="width: 200px" clearable
                              @keyup.enter.native="onSearch"/>
                </el-form-item>
                <el-form-item label="参数键名" prop="configKey">
                    <el-input v-model="selectFormModel.configKey" placeholder="参数键名" style="width: 200px" clearable
                              @keyup.enter.native="onSearch"/>
                </el-form-item>
                <el-form-item label="系统内置" prop="configType">
                    <el-select value="" v-model="selectFormModel.configType" placeholder="系统内置" style="width: 200px">
                        <el-option label="否" value="false"/>
                        <el-option label="是" value="true"/>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" plain round @click="onSearch">搜索
                    </el-button>
                    <el-button type="warning" icon="el-icon-refresh" size="mini" plain round
                               @click="onRefreshSelectForm">重置
                    </el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row class="toolbar">
            <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
                       v-permission="'system:config:add'">
                新增
            </el-button>
            <el-button type="info" icon="el-icon-edit" :disabled="dialog.isBatchEditDisabled" size="mini" plain
                       @click="handleEdit" v-permission="'system:config:edit'"> 编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" :disabled="dialog.isBatchRemoveDisabled" size="mini" plain
                       @click="handleBatchDelete" v-permission="'system:config:remove'"> 删除
            </el-button>
            <el-button type="warning" icon="fa fa-download" size="mini" plain @click="handleExport"
                       v-permission="'system:config:export'"> 导出
            </el-button>
        </el-row>
        <data-table ref="dataTable"
                    :options="options"
                    :operates="operates"
                    :api="getConfigList"
                    :columns="columns"
                    :query="selectFormModel"
                    @handleSelectionChange="handleSelectionChange"
        />

        <el-dialog :title="dialog.title" :visible.sync="dialog.dialogFormVisible"
                   :modal-append-to-body="false"
                   @close="closeDialog"
                   :destroy-on-close="false" width="600px">
            <el-form :model="configModel" ref="configForm" label-width="100px" :rules="configFormRules" size="small">

                <el-form-item label="参数名称" prop="configName">
                    <el-input v-model="configModel.configName" placeholder="参数名称"/>
                </el-form-item>
                <el-form-item label="参数键名" prop="configKey">
                    <el-input v-model="configModel.configKey" placeholder="参数键名"/>
                </el-form-item>
                <el-form-item label="参数键值" prop="configValue">
                    <el-input v-model="configModel.configValue" placeholder="参数键值"/>
                </el-form-item>
                <el-form-item label="系统内置" prop="configType">
                    <el-switch v-model="configModel.configType" active-color="#13ce66" inactive-color="#ff4949"
                               active-text="是"
                               inactive-text="否"/>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="configModel.remark" placeholder="备注" type="textarea" :autosize="{ minRows: 2}"
                              maxlength="500"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialog.dialogFormVisible=false" size="medium">取 消</el-button>
                <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts">
    import {Component, Ref, Vue} from "vue-property-decorator";
    import DataTable from "@/components/DataTable/DataTable.vue";
    import {
        addConfig,
        checkConfigKeyUnique,
        exportConfig,
        getConfigList,
        removeConfig,
        updateConfig
    } from "@/api/config";

    @Component({
        components: {
            DataTable
        }
    })
    export default class Config extends Vue {
        private getConfigList: Function = getConfigList;
        @Ref("dataTable") private dataTable: any;
        @Ref("selectForm") private selectForm: any;
        @Ref("configForm") private configForm: any;
        /*搜索框*/
        selectFormModel: any = {
            configName: "",
            configKey: "",
            configType: ""
        };
        /*列信息*/
        columns: any = [
            {label: "ID", prop: "id", sortable: "custom"},
            {label: "参数名称", prop: "configName", sortable: "custom", showOverflowTooltip: true},
            {label: "参数键名", prop: "configKey", sortable: "custom", showOverflowTooltip: true},
            {label: "参数键值", prop: "configValue", sortable: "custom", showOverflowTooltip: true},
            {
                label: "系统内置", prop: "configType", sortable: "custom", render: function (createElement, row) {
                    if (row && row.row && row.row.configType) {
                        return createElement('span', ['是']);
                    } else {
                        return createElement('span', ['否']);
                    }
                }
            },
            {label: "备注", prop: "remark", sortable: "custom", showOverflowTooltip: true},
            {label: "创建者", prop: "createBy", sortable: "custom"},
            {label: "创建时间", prop: "createTime", width: 160}
        ];

        // table 的参数
        options: any = {
            stripe: true, // 是否为斑马纹 table
            loading: false, // 是否添加表格loading加载动画
            highlightCurrentRow: true, // 是否支持当前行高亮显示
            multipleSelect: true, // 是否支持列表项选中功能
            defaultSort: {
                prop: 'id',
                order: 'ascending'
            }
        };
        /*操作栏*/
        operates: any = {
            title: "操作",
            width: "auto",
            fixed: "right",
            list: [
                {
                    label: "编辑",
                    type: "warning",
                    icon: "el-icon-edit",
                    plain: true,
                    disabled: (index, row) => {
                        return false;
                    },
                    permission: "system:config:edit",
                    method: (index, row) => {
                        this.handleEdit(index, row);
                    }
                },
                {
                    label: "删除",
                    type: "danger",
                    icon: "el-icon-delete",
                    plain: true,
                    disabled: (index, row) => {
                        return false;
                    },
                    permission: "system:config:remove",
                    method: (index, row) => {
                        this.handleDelete(index, row);
                    }
                }
            ]
        };
        dialog: any = {
            dialogFormVisible: false,
            title: "对话框",
            isEdit: false,
            isBatchEditDisabled: true,
            isBatchRemoveDisabled: true,
            formData: []
        };

        configModel: any = {
            configName: "",
            configKey: "",
            configValue: "",
            configType: false,
            remark: ""
        };

        /*验证参数key是否唯一*/
        validateConfigKeyUnique(rule: any, value: any, callback: any) {
            checkConfigKeyUnique({
                configKey: value,
                id: this.configModel.id
            }).then((res: any) => {
                if (res.data && res.data === '0') {
                    callback();
                } else {
                    callback(new Error('参数键名已经存在'));
                }
            }).catch((err: any) => {
                console.log(err);
                callback(new Error('参数键名已经存在'));
            })
        }

        configFormRules: any = {
            configName: [
                {required: true, message: "参数名称不能为空", trigger: ["blur", "change"]}
            ],
            configKey: [
                {required: true, message: "参数键名不能为空", trigger: ["blur", "change"]},
                {validator: this.validateConfigKeyUnique, trigger: 'blur'}
            ],
            configValue: [
                {required: true, message: "参数键值不能为空", trigger: ["blur", "change"]}
            ]
        };

        /*新增*/
        handleAdd() {
            this.dialog.title = "新增参数配置";
            this.dialog.isEdit = false;
            this.dialog.dialogFormVisible = true;
        }

        /*编辑*/
        handleEdit(index: number, row: any) {
            this.dialog.title = "编辑参数配置";
            this.dialog.isEdit = true;

            this.configModel = Object.assign({}, row || this.dialog.formData[0]);
            this.dialog.dialogFormVisible = true;
        }

        /*删除*/
        handleDelete(index: number, row: any) {
            this.$confirm("确定要删除该参数配置？", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                return removeConfig({"ids": [row.id]});
            }).then((response: any) => {
                this.dataTable.refresh();
                this.$message.success(response.msg);
            }).catch((e) => {
                console.log(e);
            });
        }

        /*批量删除*/
        handleBatchDelete() {
            //删除
            this.$confirm("确定要删除选定参数配置？", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                const ids: Array<any> = [];
                this.dialog.formData.forEach((item, index) => {
                    ids[index] = item.id;
                });
                return removeConfig({"ids": ids});
            }).then((response: any) => {
                this.dataTable.refresh();
                this.$message.success(response.msg);
            }).catch((e) => {
                console.log(e);
            });
        }

        submitForm(): void {
            this.configForm.validate((valid: boolean) => {
                if (valid) {
                    if (this.dialog.isEdit) {
                        //编辑
                        updateConfig(this.configModel).then((response: any) => {
                            this.dataTable.refresh();
                            this.reset();
                            this.dialog.dialogFormVisible = false;
                            this.$message.success(response.msg);
                        }).catch((e) => {
                            console.log(e);
                        });
                    } else {
                        //新增
                        addConfig(this.configModel).then((response: any) => {
                            this.dataTable.refresh();
                            this.reset();
                            this.dialog.dialogFormVisible = false;
                            this.$message.success(response.msg);
                        }).catch((e) => {
                            console.log(e);
                        });
                    }
                }
            });
        }


        /*选中事件*/
        handleSelectionChange(val): void {
            if (val) {
                this.dialog.isBatchRemoveDisabled = val.length <= 0;
                this.dialog.isBatchEditDisabled = val.length !== 1;
            }
            this.dialog.formData = val;
        }

        /*搜索*/
        onSearch(): void {
            this.dataTable.refresh();
        }

        /*重置*/
        onRefreshSelectForm(): void {
            //恢复搜索默认信息
            this.selectForm.resetFields();
            this.onSearch();
        }

        /*重置表单*/
        reset(): void {
            this.configModel = {
                configName: "",
                configKey: "",
                configValue: "",
                configType: false,
                remark: ""
            };
            (this as any).resetForm("configForm");
        }

        /*关闭对话框*/
        closeDialog() {
            this.$nextTick(() => {
                this.reset();
            });
        }

        /*导出excel*/
        handleExport(): void {
            this.$confirm('确定要导出当前查询的所有参数信息吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info'
            }).then(() => {
                this.selectFormModel.pageNum = null;
                this.selectFormModel.pageSize = null;
                this.selectFormModel.orderByColumn = 'id';
                this.selectFormModel.isAsc = 'asc';

                return exportConfig(this.selectFormModel);
            }).then((response: any) => {
                console.log(response);
                if (response && response.data) {
                    (this as any).$download(response.data.fileName);
                }
            }).catch((e) => {
                console.log(e);
            });
        }
    }
</script>

<style scoped lang="scss">

</style>

